package client

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"net"
)

var db *sql.DB
var err error

type loginInfo struct {
	Id       int
	Number   string
	Password string
	Status   int
}

type CliMessage struct {
	kind string
	data interface{}
}

type userList struct {
	id      int
	user_id int
	own_id  int
}

//密码错误 = 1
//已经在线 = 2
//允许登录 = 3
type ansStruct struct {
	AnswerStatus int
	AnswerData   string
}

type UserOp interface {
	doLogin(conn net.Conn)
}

func (u *User) doLogin(conn net.Conn) {
	sendMes := CliMessage{
		kind: "login",
		data: loginInfo{
			Number:   u.Number,
			Password: u.Password,
		},
	}
	sendJson, err := json.Marshal(sendMes)
	if err != nil {
		fmt.Println("sendMes to json err", err)
		return
	}
	conn.Write(sendJson)
	buf := make([]byte, 1024)
	n, err := conn.Read(buf)
	if err != nil {
		fmt.Println("accept message err", err)
		return
	}

	//analysis the fullback message
	var ans ansStruct
	acceptMes := string(buf[0:n])
	err2 := json.Unmarshal([]byte(acceptMes), ans)
	if err2 != nil {
		fmt.Println("accept message unjson err", err2)
		return
	}
	if ans.AnswerStatus == 1 {
		fmt.Println("password err")
		return
	}
	if ans.AnswerStatus == 2 {
		fmt.Println("you already online")
		return
	}

	var list []userList
	list = make([]userList, 20)

	err1 := json.Unmarshal([]byte(ans.AnswerData), list)
	if err1 != nil {
		fmt.Println("get user list err", err1)
		return
	}
	fmt.Println(list)
}
